﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using ForumsBrowser.ObjectGateway;
using System.Windows;
using ForumsBrowser.BusinessObjects;

namespace ForumsBrowser
{

    public class ImageConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            
            if (targetType != typeof(ImageSource))
                throw new InvalidOperationException("Return type must be BitmapSource");
            string url = value as string;
            if (!string.IsNullOrEmpty(url))
            {
                System.Drawing.Bitmap image = (System.Drawing.Bitmap)Gateway.ImageGet(url);
                if (image != null)
                {
                    System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                        image.GetHbitmap(),
                        IntPtr.Zero,
                        Int32Rect.Empty,
                        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                    return bitmapSource;
                }
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }

        #endregion
    }
}
